from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from user.models import *
from .ser import *


# Create your views here.

class CateM(APIView):
    def get(self, request):
        # 获取一级分类
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list = []

        # 循环获取二级
        for i in cates:
            dict = {}
            dict['id'] = i.id  # 一级ID
            dict['name'] = i.name  # 一级NAME
            two = i.subs.all()  # 通过一级反查询二级数据
            twolist = []
            # 循环二级获取三级
            for j in two:
                twodict = {}
                twodict['id'] = j.id  # 二级ID
                twodict['name'] = j.name  # 二级NAME
                three = j.subs.all()  # 通过二级反查询三级数据
                # 序列化器转成JSon的
                ser = CateSer(three, many=True)
                twodict['subs'] = ser.data  # 把三级数据添加给二级字典
                twolist.append(twodict)  # 再添加到二级列表
            dict['subs'] = twolist  # 把二级和三级数据加到一级字典
            list.append(dict)  # 再添加给一级列表
        goodslist = []
        for j in cates:
            dict1 = {}
            dict1['id'] = j.id
            dict1['name'] = j.name
            dict1['pic'] = str(j.pic)
            twos = j.subs.all()
            twoser = CateSer(twos, many=True)
            dict1['two'] = twoser.data
            # 获取三级
            threes = Category.objects.filter(top_parent=j.id, level=3).all()
            threeser = CateSer(threes, many=True)
            dict1['three'] = threeser.data
            # 获取商品
            sorted = request.GET.get('sorted')
            topid = request.GET.get('topid')
            goods = Goods.objects.filter(category1_id=j.id, home_show=1).all()


            if sorted:
                if int(topid) == int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id, home_show=1).order_by(sorted).all()
            ser = GoodSer(goods, many=True)
            dict1['goods'] = ser.data
            goodslist.append(dict1)
        return Response({'code': 200, 'catelist': list, 'goodlist': goodslist})
